package org.example.mp4demo.controller;

import cn.hutool.core.collection.CollUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.mp4demo.mp4.CustomMovieCreator;
import org.mp4parser.Container;
import org.mp4parser.muxer.Movie;
import org.mp4parser.muxer.Track;
import org.mp4parser.muxer.builder.FragmentedMp4Builder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = "上传", description = "上传")
@RequestMapping("/api")
@Slf4j
public class UploadController {
    @RequestMapping("/uploadAndDownload")
    @ApiOperation("上传")
    //测试视频下载 https://www.alipan.com/s/zdeQNdEy6Ph
    //mp4info工具下载 https://www.alipan.com/s/FBN41vaHK8E
    //建议使用postman或者apiFox获取生成后的文件 调用 http://localhost:8080//api/uploadAndDownload,下载后使用mp4info查看moov是否
    //在最前方
    public ResponseEntity<StreamingResponseBody> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        //根据文件名判断文件类型是否是Mp4,精准判断可以是用tika
        if (originalFilename.endsWith(".mp4")) {
            try {
                byte[] newMp4Bytes = generateNewMp4(file);
                //将newMp4Bytes转为新的mp4文件返回给前端
                StreamingResponseBody stream = outputStream -> {
                    try (InputStream inputStream = new ByteArrayInputStream(newMp4Bytes)) {
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                };
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=good.mp4")
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(stream);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.info(originalFilename);
        return null;
    }

    private byte[] generateNewMp4(MultipartFile file) {
        File outPutFile = null;
        // 创建临时文件
        File convFile = null;
        List<Track> tracks = new ArrayList<>();
        try {
            outPutFile = File.createTempFile("tempOut", file.getOriginalFilename());
            convFile = File.createTempFile("tempIn", file.getOriginalFilename());
            file.transferTo(convFile);
            // 创建Movie对象
            Movie movie = CustomMovieCreator.build(convFile.getPath());
            // 获取所有轨道
            tracks = movie.getTracks();
            // 创建一个新的Movie对象
            Movie newMovie = new Movie();
            for (Track track : tracks) {
                newMovie.addTrack(track);
            }
            // 构建 MP4 文件
            try (FileOutputStream fos = new FileOutputStream(outPutFile);
                 FileChannel fc2 = fos.getChannel()) {
                Container mp4file = new FragmentedMp4Builder().build(newMovie);
                mp4file.writeContainer(fc2);
            }
            byte[] fileBytes = getFileBytes(outPutFile);
            return fileBytes;
        } catch (IOException e) {
            log.error("文件转换异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }finally {
            if(CollUtil.isNotEmpty(tracks)){
                for (Track track : tracks) {
                    try {
                        //track也需要关闭,结合randomAccess一起关闭,则能解除文件占用
                        track.close();
                        log.info("关闭track：{}",track.getHandler());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            if (outPutFile.exists()) {
                boolean delete = outPutFile.delete();
                log.info("删除outPut临时文件：{}",delete);
            }
            if (convFile.exists()) {
                boolean delete = convFile.delete();
                log.info("删除inPut临时文件：{}",delete);
            }
        }
    }

    /**
     * 使用 BufferedInputStream 和 ByteArrayOutputStream 分块读取文件内容，避免一次性加载整个文件,造成直接内存溢出
     * @param file
     * @return
     * @throws IOException
     */
    private static byte[] getFileBytes(File file) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            return bos.toByteArray();
        } catch (FileNotFoundException e) {
            log.error("文件不存在", e);
            throw new RuntimeException(e);
        } catch (IOException e) {
            log.error("文件读取失败", e);
            throw new RuntimeException(e);
        }
    }
}
